import {
  plainToInstance,
  instanceToPlain,
} from 'class-transformer'

class User {
  name: string
  age: number
}

const plainUser = { name: 'zs', age: 66 , address: 'cn'}

// 基于普通对象 plainUser 返回一个 User 类的实例
const user = plainToInstance(User, plainUser)
console.log(user instanceof User, user) // true User { name: 'zs', age: 66, address: 'cn' }

// 基本原理
// function plainToInstance2(Clazz, obj) {
//   let instance = new Clazz
//   for (let key in obj) {
//     instance[key] = obj[key]
//   }
//   return instance
// }

// 将类的实例转换为普通对象
const obj = instanceToPlain(user)
console.log(obj instanceof User, obj) // false { name: 'zs', age: 66, address: 'cn' }
